// pages/tjht/tjht.
var util = require('../../utils/util.js');
var common = require('../../utils/common.js');
const app = getApp();;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    // isLogin:true,
    // srmc: "",//自定义费用输入名称，已取消
    // srjg: "",//自动义费用输入价格
    // srcs: "",//自定义费用输入初始参数
    // yjmc: "",//自动义押金输入名称，已取消
    // yjjg: "",//自定义押金输入价格
    beizhu: "",//备注
    phone: "",//输入电话号码
    username: "",//姓名
    sex: "男",//性别
    men: true,//男
    women: false,//女
    idnumber: "",//身份证号
    memberId: "",//用户id
    fyarray: [],//房源分组列表
    fyindex: 0,//选中的房源下表
    roomTypeArray: [],//户型列表
    roomTypeIndex: 0,//选中户型
    fanghao: "",//房号
    startTime: "",//合同开始时间
    finishTime: "",//合同截止时间
    leaveMonth: 0,//合同剩余月数
    rent: "",//每月租金
    fkfsArray: [],//付款方式列表
    fkfsIndex: 0,//选中的付款方式
    yqsk: true,//是否一起收款
    fylist: [],//费用列表
    fylistChoose: [],//传给费用选择页面
    yjlist: [],//押金列表
    yjlistChoose: [],//传给押金选择页面
    sffsArray:["固定","抄表"],
    sffsIndex:5,
    isAgree: false,//是否同意相关协议
    files: [],//身份证图片列表
    src: ""//签名图片地址
  },
  phoneInput: function (e) {//电话号码输入监听
    this.setData({
      phone: e.detail.value
    })
  },
  phoneQuery: function () {//根据号码查询用户信息
    var that = this;
    wx.showLoading({
      title: '加载中'
    })
    wx.request({
      url: app.globalData.url + '/wx/user/checkMember',
      data: {
        token: wx.getStorageSync('token'),
        mobile: this.data.phone
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: res => {
        if (res.data.success == true) {
          if (res.data.data.sex == "女") {
            that.setData({
              sex: "女",
              women: true,
              men: false
            })
          } else {
            that.setData({
              sex: "男",
              women: false,
              men: true
            })
          }

          var idcardImg = that.data.files;

          if (res.data.data.idCardFace != null) {
            idcardImg.push(res.data.data["idCardFace"]);
          }

          if (res.data.data.idCardBack != null) {
            idcardImg.push(res.data.data["idCardBack"]);
          }

          that.setData({
            files: idcardImg
          })

          if (res.data.data.username != null) {
            that.setData({
              username: res.data.data.username
            })
          }

          if (res.data.data.idnumber != null) {
            that.setData({
              idnumber: res.data.data.idnumber
            })
          }

          if (res.data.data.memberId != null) {
            that.setData({
              memberId: res.data.data.memberId
            })
          }
        } else {
          wx.showModal({
            content: res.data.msg + "，请手动输入相关信息",
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                return;
              }
            }
          });
        }
      },
      fail: res => {
        wx.showToast({
          title: '租户信息获取失败',
          image: '../../image/shibai.png',
          duration: 2000
        })
      },
      complete: res => {
        wx.hideLoading()
      }
    })
  },
  radioChange: function (e) {//性别单选时间
    this.setData({
      sex: e.detail.value
    })
    if (e.detail.value == "男") {
      this.setData({
        men: true,
        women: false
      })
    } else {
      this.setData({
        men: false,
        women: true
      })
    }
    console.log(this.data.sex);
  },
  hxPickerChange: function (e) {//户型选择事件
    this.setData({
      roomTypeIndex: e.detail.value
    })
  },
  fkPickerChange: function (e) {//付款方式选择事件
    this.setData({
      fkfsIndex: e.detail.value
    })
  },
  sffs: function (e) {//费用收费方式选择事件
    this.setData({
      sffsIndex: e.detail.value
    })
    var array = this.data.fylist;
    for (var i = 0; i < array.length; i++) {
      if (array[i].itemName == e.currentTarget.dataset.type) { 
        array[i].chargetype = (this.data.sffsArray[this.data.sffsIndex] == "固定" ? 1:0 ); 
      }
    }
    this.setData({
      fylist: array
    })
  },
  startDateChange: function (e) {//合同开始时间选择事件
    var leaveMonth = this.getMch(e.detail.value, this.data.finishTime)
    this.setData({
      startTime: e.detail.value,
      leaveMonth: leaveMonth
    })
  },
  finishDateChange: function (e) {//合同结束时间选择事件
    if (e.detail.value < this.data.startTime) {
      wx.showModal({
        title: '提示',
        content: '截止时间不能小于开始时间',
      })
    } else {
      var leaveMonth = this.getMch(this.data.startTime, e.detail.value)
      this.setData({
        finishTime: e.detail.value,
        leaveMonth: leaveMonth
      })
    }
  },
  switchChange: function (e) {//是否一起收租
    this.setData({
      yqsk: e.detail.value
    })
  },
  deleteFylist: function (e) {//删除费用项
    var that = this;
    wx.showModal({
      title: '删除提示',
      content: '确定删除' + e.currentTarget.dataset.type + '选项吗？',
      confirmText: "确定",
      cancelText: "取消",
      success: function (res) {
        console.log(res);
        if (res.confirm) {
          var newFylist = that.data.fylist;
          for (var i = 0; i < newFylist.length; i++) {
            if (newFylist[i].itemName == e.currentTarget.dataset.type) {
              newFylist.splice(i, 1);
            }
          }
          that.setData({
            fylist: newFylist
          })
          app.globalData.fylist = newFylist
        } else {
          return;
        }
      }
    });
  },
  bindAgreeChange: function (e) {//是否同意协议
    this.setData({
      isAgree: !!e.detail.value.length
    });
  },
  chooseImage: function (e) {//选择图片上传
    var that = this;
    wx.chooseImage({
      count: 2,
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        that.setData({
          files: that.data.files.concat(res.tempFilePaths)
        });
      }
    })
  },
  previewImage: function (e) {//预览图片
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: this.data.files // 需要预览的图片http链接列表
    })
  },
  deleteImg: function (e) {//删除图片
    var list = this.data.files;
    list.splice(e.currentTarget.dataset.index, 1)
    this.setData({
      files: list
    });
  },
  // srmc: function (e) {//自定义费用名称输入监听，已取消
  //   this.setData({
  //     srmc: e.detail.value
  //   })
  // },
  // srjg: function (e) {//自定义费用价格输入监听
  //   this.setData({
  //     srjg: e.detail.value
  //   })
  // },
  // srcs: function (e) {//自定义费用输入初数监听
  //   this.setData({
  //     srcs: e.detail.value
  //   })
  // },
  // addFylist: function (e) {//自定义费用添加
  //   var that = this;
  //   if (this.data.srmc == "" || this.data.srjg == "") {
  //     wx.showModal({
  //       content: '名称或价格不能为空！',
  //       showCancel: false,
  //       success: function (res) {
  //         if (res.confirm) {
  //           return;
  //         }
  //       }
  //     });
  //   } else {
  //     wx.showModal({
  //       title: '添加提示',
  //       content: '确定添加' + that.data.srmc + '选项吗？',
  //       confirmText: "确定",
  //       cancelText: "取消",
  //       success: function (res) {
  //         console.log(res);
  //         if (res.confirm) {
  //           var fy = {};
  //           fy["type"] = that.data.srmc;
  //           fy["price"] = that.data.srjg;
  //           fy["initData"] = that.data.srcs;
  //           var newFylist = that.data.fylist;
  //           that.setData({
  //             fylist: newFylist.concat(fy)
  //           })
  //           that.setData({
  //             srmc: "",
  //             srjg: "",
  //             srcs: ""
  //           })
  //         } else {
  //           return;
  //         }
  //       }
  //     });
  //   }
  // },
  fyjg: function (e) {//监听相关费用的价格输入
    var array = this.data.fylist;
    for (var i = 0; i < array.length; i++) {
      if (array[i].itemName == e.currentTarget.dataset.type) {
        array[i].unitCost = parseFloat(e.detail.value);
      }
    }
    this.setData({
      fylist: array
    })
  },
  fycs: function (e) {//监听相关费用的初数输入
    var array = this.data.fylist;
    for (var i = 0; i < array.length; i++) {
      if (array[i].itemName == e.currentTarget.dataset.type) {
        array[i].nowNum = parseFloat(e.detail.value)
      }
    }
    this.setData({
      fylist: array
    })
  },
  deleteYjlist: function (e) {//删除押金项
    var that = this;
    wx.showModal({
      title: '删除提示',
      content: '确定删除' + e.currentTarget.dataset.type + '选项吗？',
      confirmText: "确定",
      cancelText: "取消",
      success: function (res) {
        if (res.confirm) {
          var newYjlist = that.data.yjlist;
          for (var i = 0; i < newYjlist.length; i++) {
            if (newYjlist[i].itemNme == e.currentTarget.dataset.type) {
              newYjlist.splice(i, 1);
            }
          }
          console.log(newYjlist);
          that.setData({
            yjlist: newYjlist
          })
          app.globalData.yjlist = newYjlist;
        } else {
          return;
        }
      }
    });
  },
  yjjg: function (e) {//监听相关押金的价格输入
    var array = this.data.yjlist;
    for (var i = 0; i < array.length; i++) {
      if (array[i].itemName == e.currentTarget.dataset.type) {
        array[i].unitCost = parseFloat(e.detail.value);
        array[i].chargetype = 0
      }
    }
    this.setData({
      yjlist: array
    })
  },
  // yjmc: function (e) {//监听自定义押金名称输入，已取消
  //   this.setData({
  //     yjmc: e.detail.value
  //   })
  // },
  // yjjg: function (e) {//监听自定义押金价格输入
  //   this.setData({
  //     yjjg: e.detail.value
  //   })
  // },
  // addYjlist: function (e) {//自定义押金添加
  //   var that = this;
  //   if (this.data.yjmc == "" || this.data.yjjg == "") {
  //     wx.showModal({
  //       content: '名称或价格不能为空！',
  //       showCancel: false,
  //       success: function (res) {
  //         if (res.confirm) {
  //           return;
  //         }
  //       }
  //     });
  //   } else {
  //     wx.showModal({
  //       title: '添加提示',
  //       content: '确定添加' + that.data.yjmc + '选项吗？',
  //       confirmText: "确定",
  //       cancelText: "取消",
  //       success: function (res) {
  //         console.log(res);
  //         if (res.confirm) {
  //           var yj = {};
  //           yj["type"] = that.data.yjmc;
  //           yj["price"] = that.data.yjjg;
  //           var newYjlist = that.data.yjlist;
  //           that.setData({
  //             yjlist: newYjlist.concat(yj)
  //           })
  //           that.setData({
  //             yjmc: "",
  //             yjjg: ""
  //           })
  //         } else {
  //           return;
  //         }
  //       }
  //     });
  //   }
  // },
  beizhu: function (e) {//监听备注输入，不需要预先展示的也可使用表单一次性获取相关输入框的value值
    this.setData({
      beizhu: e.detail.value
    })
  },
  fanghao: function (e) {//监听房号输入
    this.setData({
      fanghao: e.detail.value
    })
  },
  username: function (e) {//监听姓名输入
    this.setData({
      username: e.detail.value
    })
  },
  idnumber: function (e) {//监听身份证号输入
    this.setData({
      idnumber: e.detail.value
    })
  },
  rent: function (e) {//监听每月租金输入
    this.setData({
      rent: e.detail.value
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {//页面加载则获取房源分组
    var startTime = util.formatTime(new Date());
    var finishTime = util.formatTimeOneYear(new Date());
    startTime = startTime.split(" ")[0].replace(/\//g, "-");
    finishTime = finishTime.split(" ")[0].replace(/\//g, "-");
    var leaveMonth = this.getMch(startTime, finishTime);
    this.setData({
      startTime: startTime,
      finishTime: finishTime,
      leaveMonth: leaveMonth
    })

    var that = this;
    var url = "/wx/contract/initContractPage";
    var data = {};
    var success = function (res) {
      console.log(res);
      // var yjdata = res.data.data.foregiftList;
      var yjdata = [{ "id": 1, "key": "2", "value": "房屋押金", "pid": 1, "sequence": 1 }];
      var change={
        "id":"id",
        "key":"itemKey",
        "value":"itemName",
        "pid":"pid",
        "sequence":"sequence"
      }
      var fydata = res.data.data.chargeItemList;
      for(var i =0;i<fydata.length;i++){
        that.replace(fydata[i], change);
      }

      for (var i = 0; i < yjdata.length;i++){
        that.replace(yjdata[i], change);
      }
      
      console.log(fydata);
      that.setData({
        fyarray: res.data.data.houses,
        roomTypeArray: res.data.data.houseTypeList,
        yjlistChoose: yjdata,
        fylistChoose: fydata,
        fkfsArray: res.data.data.chargemodeList
      })
    };

    common._get(url, data, success)
    // wx.showLoading({
    //   title: '加载中',
    // })
    // wx.request({
    //   url: app.globalData.url + '/wx/house/houselist',
    //   data: {
    //     token: wx.getStorageSync('token')
    //   },
    //   header: {
    //     'content-type': 'application/json' // 默认值
    //   },
    //   success: function (res) {
    //     if (res.data.code == "401") {
    //       app.timeOutLogin(res);
    //       that.onLoad();
    //     } else {
    //       if (res.data.success == true) {
    //         var houseList = res.data.data.list;

    //         console.log(houseList);

    //         var newArray = that.data.fyarray;
    //         for (var i = 0; i < houseList.length; i++) {
    //           var houseJson = {};
    //           houseJson["houseId"] = houseList[i].houseId;
    //           houseJson["name"] = houseList[i].houseName;
    //           newArray.push(houseJson);
    //         }
    //         startTime = startTime.split(" ")[0].replace(/\//g, "-");
    //         finishTime = finishTime.split(" ")[0].replace(/\//g, "-");
    //         var leaveMonth = that.getMch(startTime, finishTime);
    //         that.setData({
    //           fyarray: newArray,
    //           startTime: startTime,
    //           finishTime: finishTime,
    //           leaveMonth: leaveMonth
    //         })

    //       } else {
    //         wx.showToast({
    //           title: res.data.msg,
    //           image: '../../image/shibai.png',
    //           duration: 2000
    //         })
    //       }
    //     }
    //   },
    //   fail: function (res) {
    //     wx.showToast({
    //       title: '房源分组获取失败',
    //       image: '../../image/shibai.png',
    //       duration: 2000
    //     })
    //   },
    //   complete: res =>
    //     wx.hideLoading()
    // })
  },
  getMch: function (startTime, finishTime) {//处理合同开始时间，结束时间，剩余月数
    var beginDate = startTime.split("-");//拆分开始日期的年月日     
    var endDate = finishTime.split("-");//拆分结束日期的年月日
    var bMonth = parseInt(beginDate[0]) * 12 + parseInt(beginDate[1]);//得到开始日期的月数     
    var eMonth = parseInt(endDate[0]) * 12 + parseInt(endDate[1]);//得到结束日期的月数     
    var totalMonth = Math.abs(eMonth - bMonth);//获取月数     
    return totalMonth;
  },
  toTjfy: function () {//跳转到添加费用项
    var fylistChoose = JSON.stringify(this.data.fylistChoose);
    wx.navigateTo({
      url: '../fyx/fyx?fylist=' + fylistChoose,
    })
  },
  toTjyj: function () {
    var yjlistChoose = JSON.stringify(this.data.yjlistChoose);
    wx.navigateTo({
      url: '../yjx/yjx?yjlist=' + yjlistChoose,
    })
  },
  tjht: function (e) {
    var roomId = this.getRoomId();
    var url = "/wx/contract/save";
    var gifts=[];
    for (var i = 0; i < this.data.yjlist.length;i++){
        var json={
          // "id": this.data.yjlist[i].id,
          "itemKey": this.data.yjlist[i].itemKey,
          "itemName": this.data.yjlist[i].itemName,
          "chargetype": this.data.yjlist[i].chargetype,
          "unitCost": this.data.yjlist[i].unitCost
        }
        gifts.push(json);
    }

    var items = [];
    for (var i = 0; i < this.data.fylist.length; i++) {
      var json = {
        // "id": this.data.fylist[i].id,
        "itemKey": this.data.fylist[i].itemKey,
        "itemName": this.data.fylist[i].itemName,
        "chargetype": this.data.fylist[i].chargetype,
        "nowNum": this.data.fylist[i].nowNum,
        "unitCost": this.data.fylist[i].unitCost
      }
      items.push(json);
    }

    var data = {
      sex: this.data.sex=="女"?0:1,
      starttime: this.data.startTime,
      monthlyfee: parseFloat(this.data.rent),
      chargemode: parseFloat(this.data.fkfsArray[this.data.fkfsIndex].key),
      remark: this.data.beizhu,
      memberId: this.data.memberId,
      mobile: this.data.phone,
      username: this.data.username,
      endtime: this.data.finishTime,
      // endtime: "2011-11-11 00:00:00",
      gifts: gifts,
      roomId: roomId,
      idNumber: this.data.idnumber,
      items: items
    };

    console.log(data);

    var success = function (res) {
      console.log(res);
      if(res.data.success==true){
        wx.showToast({
          title: '提交成功',
        })
      }else{
        wx.showToast({
          title: '提交失败',
        })
      }
      
    };
    if (roomId != "") {
      common._get(url, data, success)
    }

  },
  getRoomId: function (e) {
    var that = this;
    var roomId = "";
    var fyarray = that.data.fyarray;
    for (var i = 0; i < fyarray.length; i++) {
      if (fyarray[i].id == fyarray[that.data.fyindex].id) {
        for (var j = 0; j < fyarray[i].rooms.length; j++) {
          if (fyarray[i].rooms[j].roomcode == that.data.fanghao) {
            roomId = fyarray[i].rooms[j].id;
          }
        }
      }
    }

    if (roomId != "") {
      return roomId
    } else {
      wx.showToast({
        title: '房间不存在',
        image: '../../image/shibai.png',
      })
      return ""
    }
  },
  replace: function (target, change){
    for (var key in target) {
      target[change[key]] = target[key];
      if (change[key]!=key){
        delete target[key];
      } 
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {//页面展示获取相关数据
  var fee = wx.getStorageSync("fee") 
    this.setData({
      src: app.globalData.signSrc,
      fylist: app.globalData.fylist,
      yjlist: app.globalData.yjlist
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})